package blog.controller;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageInfo;

import blog.entity.Article;
import blog.entity.Category;
import blog.entity.Tag;
import blog.entity.User;
import blog.service.ArticleService;
import blog.service.CategoryService;
import blog.service.TagService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;

@Controller
@RequestMapping("/article")
public class ArticleController {
	@Resource
	private ArticleService articleService;

	@Resource
	private CategoryService categoryService;

	@Resource
	private TagService tagService;

	/*
	 * 显示全部文章
	 */
	@RequestMapping("")
	public String index(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
			@RequestParam(required = false, defaultValue = "10") Integer pageSize, ModelMap m) {

		PageInfo<Article> articePageInfo = articleService.getPageArticleList(pageIndex, pageSize);

		m.put("pageUrlPrefix", "article?pageIndex"); // 把前缀数据传给分页页面

		m.put("pageInfo", articePageInfo);
		return "Article/article-list";
	}

	/*
	 * 跳转写文章页
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET) // 提交方式如果GET则转到文章发布页
	public String go(ModelMap m) {

		// 分类列表
		List<Category> categoryList = categoryService.listCategory();

		// 标签列表
		List<Tag> tagList = tagService.listTag();

		m.put("categoryList", categoryList);
		m.put("tagList", tagList);

		return "Article/article-add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(HttpServletRequest request) {
		Article article = new Article();

		// 当前用户的id
		User user = (User) request.getSession().getAttribute("session_user");
		article.setArticleUserId(user.getUserId());

		// 文章标题
		article.setArticleTitle(request.getParameter("articleTitle"));

		// 文章内容
		article.setArticleContent(request.getParameter("articleContent"));

		// 文章摘要 HtmlUtil是 hutu 工具包提供的一个类
		String s = HtmlUtil.cleanHtmlTag(article.getArticleContent());
		article.setArticleSummary(s.length() > 150 ? s.substring(0, 150) : s);

		// 文章发布时间,修改时间
		article.setArticleCreateTime(LocalDateTime.now());
		article.setArticleUpdateTime(LocalDateTime.now());

		article.setArticleCommentCount(0);
		article.setArticleLikeCount(0);
		article.setArticleViewCount(0);

		// 默认的排序
		article.setArticleOrder(1);

		// 文章状态(草稿,或发布)
		article.setArticleStatus(Integer.parseInt(request.getParameter("articleStatus")));

		// 一级分类ID
		String articleParentCategoryId = request.getParameter("articleParentCategoryId");

		// 二级分类ID
		String articleChildCategoryId = request.getParameter("articleChildCategoryId");

		// 填充article中的分类列表
		List<Category> categoryList = new ArrayList<>(2);
		if (StrUtil.isNotEmpty(articleParentCategoryId)) {
			categoryList.add(new Category(Integer.parseInt(articleParentCategoryId)));
		}
		if (StrUtil.isNotEmpty(articleChildCategoryId)) {
			categoryList.add(new Category(Integer.parseInt(articleChildCategoryId)));
		}
		article.setCategoryList(categoryList);
		// 填充article中的标签列表
		List<Tag> tagIdList = new ArrayList<>();
		String[] tagIds = request.getParameterValues("articleTagIds");
		if (tagIds != null) {
			for (int i = 0; i < tagIds.length; i++) {
				tagIdList.add(new Tag(Integer.parseInt(tagIds[i])));
			}
		}
		article.setTagList(tagIdList);

		// 调用业务层,进行文章发布
		articleService.addArticle(article);

		// forward 或 redirect 不受前后缀的影响
		return "forward:/article";
	}

	@RequestMapping("/uploadImg") // 实际上由于返回的数据已经是JSON格式了,所以这里可以不用 @ResponseBody
	public String upload(MultipartHttpServletRequest request) throws Exception {
		// imgFile 这个名称是固定的
		MultipartFile file = request.getFile("imgFile");

		// 生成一个随机的文件名
		String newName = UUID.randomUUID().toString() + ".jpg";
		File destFile = new File("D:/imguploads/" + newName);

		String path = "http://localhost:8080/uploads/" + newName;

		file.transferTo(destFile);

		return "{\"error\":0,\"url\":\"" + path + "\"}";

	}

	/**
	 * 删除文章
	 */
	@RequestMapping(value = "/delete/{id}")
	public String deleteArticle(@PathVariable("id") Integer id) {
		articleService.deleteArticle(id);
		return "forward:/article";
	}
}
